#!/usr/bin/env bash
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:~/bin
export PATH
#=======================================#
#  清除上个赛季竞赛缓存                     #
#                                       #
#  Title: Clean up all Projects Redis   #
#  Date : 04.07.2020                    #
#  Ver: 0.3                             #
#                                       #
#=======================================#

clean_log_path=/var/log
clean_log_file=redis_clean.log
redis_host=r-wz917bqt1msm1h7uiypd.redis.rds.aliyuncs.com
redis_pwd=redisSwift2020
port=6379
project_name="FTH(字节跳动)"
pattern="Guild*"
thetime=$(date +%Y-%m-%d_%T)
REDIS_NODE=0

check_redis() {
    # check command
    system_type=$(uname -a)

    system_b="Darwin"
    system_c="centos"
    system_d="ubuntu"

    if [[ $system_type =~ $system_b ]]; then
        echo "当前系统平台：mac"
        clean_log_path=../../log
    elif [[ $system_type =~ $system_c ]]; then
        echo "当前系统平台：centos"
        if [ "$(rpm -q redis-* | wc -l)" -eq 0 ]; then
            yum -y install redis >/dev/null 2>&1
        fi
    elif [[ $system_type =~ $system_d ]]; then
        echo "当前系统平台：ubuntu"
        if [ "$(dpkg --get-selections | grep redis)" -eq 0 ]; then
            apt -y install redis
        fi
    else
        echo "${system_type}"
        exit
    fi

    # check directory
    if [ ! -d ${clean_log_path} ]; then
        mkdir -p ${clean_log_path}
    fi
}

# shellcheck disable=SC1073
clean_redis() {
    # clean redis command
    _PWD=""
    if [ "${redis_pwd}" != "" ]; then
        _PWD="-a ${redis_pwd}"
    fi

    redis-cli -h ${redis_host} ${_PWD} -p ${port} -n ${REDIS_NODE} keys ${pattern} |
    xargs redis-cli -h ${redis_host} ${_PWD} -p ${port} -n ${REDIS_NODE} del >/dev/null 2>&1

    # shellcheck disable=SC2181
    if [ $? = 0 ]; then
        echo "Project:${project_name}  IP:${redis_host} Clean Successes!"
        exit 1
    else
        echo "Project:${project_name}  IP:${redis_host} Clean Failed!"
        exit 0
    fi
}

redis_project_title() {
    # clean redis mark
    echo -e "####### Project:${project_name} IP:${redis_host} Time:${thetime} ########\n\n" >> $clean_log_path/$clean_log_file
}

main() {
    # check directory
    check_redis
    redis_project_title && clean_redis
}

main
